package com.project.common.core.utils.ffmpeg;

import com.project.common.core.config.prop.PropAttributes;
import com.project.common.core.config.prop.PropConfig;
import org.apache.commons.lang.RandomStringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FfmpegUtil {

    public static final float[] speedArr = {0.5f, 0.8f, 1.2f, 1.5f};

    /**
     * 获得音频信息
     *
     * @param filePath
     * @return
     */
    public static int getAudioLength(String filePath) {
        if (filePath == null || filePath.length() == 0) {
            return -1;
        }
        String sourceFileAllPath = PropConfig.getProperty(PropAttributes.NFS__SERVICE_FILE_SHARE_PATH) + filePath;
//        String sourceFileAllPath = "/Users/wyy/Pictures/imgTest/share" + filePath;
        String line = "ffmpeg -i " + sourceFileAllPath;
        StringBuffer strBuffer = new StringBuffer();
        try {
            System.out.println(line);
            Process pro = Runtime.getRuntime().exec(line);
            Runtime.getRuntime().runFinalization();
            Runtime.getRuntime().gc();
            InputStream is = null;
            pro.waitFor();
            if (pro.exitValue() != 0) {
                is = pro.getErrorStream();
            } else {
                is = pro.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            String s = null;
            while ((s = reader.readLine()) != null) {
                strBuffer.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        Pattern pattern = Pattern.compile("Duration: (.*?),");
        Matcher matcher = pattern.matcher(strBuffer.toString());
        String matcherResult = null;
        while (matcher.find()) {
            matcherResult = matcher.group();
        }
        if (matcherResult == null || matcherResult.length() == 0) {
            return -1;
        }
        matcherResult = matcherResult.substring(10, matcherResult.length() - 1);
        matcherResult = matcherResult.split("\\.")[0];
        String[] atom = matcherResult.split(":");
        int a = Integer.valueOf(atom[0]) * 3600 + Integer.valueOf(atom[1]) * 60 + Integer.valueOf(atom[2]);
        return a;
    }

    /**
     * 执行命令
     *
     * @param fileSpeed      变速倍数
     * @param sourceFilePath 源文件路径【调用NFS上传返回的服务器相对路径】
     * @return
     */
    public static Map<String, String> execute(Float fileSpeed, String sourceFilePath) {
        // 获取文件后缀
        String sourceFileAllPath = PropConfig.getProperty(PropAttributes.NFS__SERVICE_FILE_SHARE_PATH) + sourceFilePath;
//        String sourceFileAllPath = "/Users/wyy/Pictures/imgTest/share" + sourceFilePath;
        File sourceFile = new File(sourceFileAllPath);
        String sourceFileName = sourceFile.getName();
        String[] fileNameArr = sourceFileName.split("\\.");
        String fileNameSuffix = fileNameArr[1];

        // 获取源文件绝对路径
        String baseName = RandomStringUtils.randomAlphanumeric(18);
        String targetFileName = baseName + "." + fileNameSuffix;
        String targetFileAllPath = sourceFile.getParent() + "/" + targetFileName;


        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-i");
        commands.add(sourceFileAllPath);
        commands.add("-filter:a");
        commands.add("atempo=" + fileSpeed);
        commands.add("-vn");
        commands.add(targetFileAllPath);
        commands.add("-loglevel");
        commands.add("quiet");

        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commands);
            builder.start();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("name", targetFileName);
        returnMap.put("path", targetFileAllPath);

        return returnMap;
    }

    public static void main(String[] args) {
        int audioLength = getAudioLength("/test.mp3");
        System.out.println(audioLength);
        execute(8f, "/test.mp3");
    }
}
